#
#	All the functions used in q3_parser.rb
#

require 'rubygems'
require 'gruff'


#
# Deletes all the files from the directory listing 
# which do not match the prefix
#
def bot_pool( prefix )
	dir = (Dir.entries './genes/').sort!
	dir.delete_if do
		|file| 
		!/#{prefix}/.match file
	end
	dir
end


#
# Return the current command line characteristic
#
def get_charac arg
	arg.gsub(/=/, ' ').split
end


#
# Open a file to parse all the possible parsable characterstics
#
def open_file
	begin
		file = File.open './genes/001-R01.ini'
	rescue Errno::ENOENT
		print_error 'No bot files exist!'
	end
	file
end


#
# Print the characteristics or push them all on a list
#
def parse_characs( file, list = nil )
	characs = Array.new
	file.each do
		|line|
		charac = line.gsub(/=/, ' ').split if /=/.match(line)
		unless (charac.nil? || !(/^[\d.]+$/.match(charac[1])))
			characs.push charac[0]
			puts charac[0] unless list.nil?
		end
	end
	characs
end

#
# parse all the bots' prefixes and return them in an array
#
def parse_bots
	begin
		dir = Dir.entries './genes/'
		
		dir.delete_if do
			|file| !/\.ini/.match file
		end
	
		dir.sort!
		
		# => group the files and put them in an array
		bot_array = Array.new
		dir.each do
			|file|
			prefix = file.gsub(/-/, ' ').split[0] #=> get the prefix
			bot_array.push prefix if bot_array.last != prefix
		end
		bot_array.delete ".ini"
		
		bot_array
	rescue SystemCallError
		print_error 'Problem reading the current directory'
	end
end

#
# return the value for the given bot and characteristic
#
def parse_bot_value( file, charac )
	file = File.open './genes/' + file
	value = nil
	file.each do
		|line|
		if line.include? charac
			value = line.split[2]
			break
		end
	end
	value
end

#
# How does everything work?
#
def print_usage
	puts '== Synopsis'
	puts 'file parser for quake3 bot files'
	puts '== Usage'
	puts ' # => for generating a graph for a specific bot:'
	puts 'ruby ruby_quake_graph.rb -charac=[characeter]'
	puts ' # => for showing a list of availible parameters:'
	puts 'ruby ruby_quake_graph.rb -list'
end

# Helper function
def print_help
	print_usage
	exit
end

# Error handling
def print_error error
	puts error
	exit
end

#
# Generate and write the current graph for the
# given characteristic and values
#
def generate_graph( values, charac )
	charac = charac.capitalize

	g = Gruff::Line.new(2000)
	g.title = "Average - #{charac}"

	g.hide_dots = true
	g.data( charac, values )
	
	xaxis = {}
	1.upto 20 do |i|
		x = i * 10
		xaxis[x] = x.to_s
	end

	g.labels = xaxis
	g.minimum_value = 0
	g.maximum_value = 1
	g.write("#{charac.downcase}.png")
end


## deprecated
def parse_line( file, characteristic )
	file.each do
		|line| puts line if /characteristic/.match line
	end
end
##

